// 样式-数据-拖拉拽数据
import React from 'react';
// import DrapArea from './DrapArea';
import SortItem from './SortItem';
import { useDrop } from 'react-dnd';
import { WD_CODE, DL_CODE, WD_TYPE, DL_TYPE, DragTypes, DATE_TYPES, DATA_UNIT_TYPES } from '../EnumConfig';
import { notification } from 'antd';

declare type DragType = typeof DragTypes[number];

interface IProps {
	tip: string;
	name: string;
	config: any;
	form: any;
	onValuesChange: ( chartType: string, key: string, values: Object, configType: string ) => void;
	dragOver: ( value: string, columns?: any[], name?: string ) => void;
	onItemClick?: Function;
	currentDragNode: any;
	// 设置拖拽的是维度还是度量 默认是拖拽维度
	type?: DragType;
	// 拖入的数据的长度
	limit?: number;
	isShowSetting? : boolean;	//	是否显示设置
	isAutoDrag?: boolean;	//	拖拽字段之后，是否显示字段，主要是针对筛选字段，拖拽之后，还需要弹窗设置
}

const ItemTypes = {
	BOX: 'box',
};

const containerStyle = {
	border: 'dashed 1px #ccc',
	minHeight: '20px',
	padding: '4px 3px',
	fontSize: '12px',
};

const tipStyle = {
	color: '#929292',
	// textAlign: 'center',
	width: '100%',
	padding: '3px 0',
};

const DragContainer = ( props: IProps ) => {
	const { tip, name, config, onValuesChange, dragOver, currentDragNode, type = WD_CODE, limit, form, isShowSetting = true, isAutoDrag = true } = props;
	const { data: dataConfig } = config;
	const to = dataConfig[name] || [];

	const [ , drop ] = useDrop( {
		accept: ItemTypes.BOX,
		collect: ( monitor ) => ( {
			isOver: monitor.isOver()
		} ),
		
	} );

	const handleSort = ( dragIndex: number, hoverIndex: number ) => {
		let copyTo = Array.from( to );
		let dragItem = copyTo.splice( dragIndex, 1 );
		copyTo.splice( hoverIndex, 0, dragItem[0] );
	
		setTimeout( () => {
			
			onValuesChange( config.type, config.key, { [name]: copyTo }, 'data' );
		}, 50 );
	};

	const handleDelete = ( e, index: any ) => {
		e.stopPropagation();
		const oldValues = Array.from( dataConfig[name] || [] );
		oldValues.splice( index, 1 );
		onValuesChange( config.type, config.key, { [name]: oldValues }, 'data' );
	};

	// 设置改变时
	const handleUpdate = ( value: any, index: number, unit?: boolean ) => {
		const oldValues = Array.from( dataConfig[name] || [] );
		const oldNode = Object.assign( {}, oldValues[index] );
		oldValues.splice( index, 1, { ...oldNode, ...value } );

		if( unit ) {
			console.log( 'unit' );
			const dataUnit = getUnifiedDLUnit( oldValues );
			onValuesChange( config.type, config.key, { [name]: oldValues, [`${name}Unit`]: dataUnit }, 'data' );
		} else {
			onValuesChange( config.type, config.key, { [name]: oldValues }, 'data' );
		}
	};

	const notifyErrorMsg = ( msg ) => {
		notification.error( {
			message: '',
			description: msg,
		} );
	};

	const handleDragOver = async () => {
		if ( !currentDragNode ) {
			return;
		}
		if ( currentDragNode.childrenType === 'FOLDER' ) {
			notifyErrorMsg( '禁止拖入层级' );
			dragOver( null );
			return;
		}
		if ( limit && form.getFieldsValue()[name] && limit === form.getFieldsValue()[name].length ) {
			notifyErrorMsg( `最多可拖入${limit}个字段` );
			dragOver( null );
			return;
		}
		// 判断需要拖入的是维度还是度量
		if ( type === WD_CODE && currentDragNode.modelType !== WD_TYPE ) {
			notifyErrorMsg( '请拖入维度' );
			dragOver( null );
			return;
		}
		if ( type === 'both' && currentDragNode.modelType !== WD_TYPE && currentDragNode.modelType !== DL_TYPE ) {
			notifyErrorMsg( '请拖入维度或者度量' );
			dragOver( null );
			return;
		}
		if ( type === DL_CODE && currentDragNode.modelType !== DL_TYPE ) {
			notifyErrorMsg( '请拖入度量' );
			dragOver( null );
			return;
		}

		if ( ( type === 'date' || type === 'quotaDate' )&& DATE_TYPES.indexOf( currentDragNode.dataType.toUpperCase() ) === -1 ) {
			notifyErrorMsg( '请拖入日期类型字段' );
			dragOver( null );
			return;
		}

		const oldColumns = dataConfig[name] || [];

		const { id } = currentDragNode;
		if ( oldColumns.some( ( item ) => item.id === id ) ) {
			notifyErrorMsg( '拖入了重复的字段' );
			dragOver( null );
		} else {
			if( isAutoDrag ) {
				let newArray = [ ...oldColumns, currentDragNode ];
				form.setFieldsValue( { [name]: newArray } );
				onValuesChange( config.type, config.key, { [name]: newArray, [`${name}Unit`]: '' }, 'data' );
				dragOver( null, newArray, name );
			} else {
				dragOver( null, currentDragNode, name );
			}

		}
	};


	// 返回统一的度量设置的单位
	const getUnifiedDLUnit = ( items: Array< any > ) => {
		if( items.length === 0 ) return '';
		let dataUnit = items[0].dataUnit;
		for( let key in items ) {
			const value = items[key];
			if( value.modelType !== DL_TYPE || value.dataUnit !== dataUnit ) {
				return '';
			}
		}
		if( dataUnit ) {
			return DATA_UNIT_TYPES[ items[0].dataUnit ].label;
		} else {
			return '';
		}
	};

	return (
		<div ref={drop} style={{ ...containerStyle }} onMouseEnter={handleDragOver}>
			<div style={{ backgroundColor: '#fff' }}>
				{to.map( ( v: any, i: any ) => (
					<SortItem
						node={v}
						key={v.id}
						index={i}
						chartType={config.type}
						moveCard={handleSort}
						handleDelete={( e ) => handleDelete( e, i )}
						handleUpdate={( value, index, unit ) => handleUpdate( value, index, unit )}
						isShowSetting={isShowSetting}
						onItemClick={props.onItemClick}
					></SortItem>
				) )}
			</div>
			<div style={{ ...tipStyle, textAlign: 'center' }}>{tip}</div>
		</div>
	);
};

export default React.memo( DragContainer );
